<template>
    <div class="create" ref="create">

        <div id="content">
            <cube-scroll>
                <div id="form">
                    <cube-form
                            ref="form"
                            :model="model"
                            :schema="schema"
                            :submitAlwaysValidate="true"
                            @submit="submit"
                    ></cube-form>
                </div>
            </cube-scroll>
        </div>

        <!--S底部-->
        <div id="footer">
            <div class="row">所需{{setting.currency_name}}:{{sum}}</div>
            <div class="row" @click="createOrder">
                <i class="iconfont icon-gouwu"></i> 确认兑换
            </div>
        </div>
        <!--E底部-->

        <!--S子页面-->
        <transition :name="transition_name">
            <router-view class="children" />
        </transition>
        <!--E子页面-->

    </div>
</template>

<script>
    import goodsName from "./components/goods-name/GoodsName";
    import areas from "./components/area/Area";
    import takeAddress from "./components/address/Address";
    import plugin from "../../../../../../util/plugin";
    import { mapState } from "vuex";
    import store from "../../../../../../store";
    export default {
        name: "create",
        data(){
            return {
                goods_id:0,
                goods:{}, //商品详情
                transition_name:"",
                model:{
                    name:"",
                    number:1,
                    take_name:"",
                    take_phone:"",
                    area:[],
                    address:"",
                    plugin_address:""
                },
                schema:{
                    fields: [
                            {
                                type:goodsName,
                                modelKey:'name'
                            },
                            {
                                type:'input',
                                modelKey:'number',
                                label:'兑换数量',
                                props:{
                                    type:'text',
                                    placeholder:'兑换数量'
                                },
                                rules:{
                                    required:true,
                                    type:'number',
                                    max:100,
                                    min:1,
                                    pattern:/^\d+$/
                                },
                                messages:{
                                    required:'请输入兑换数量',
                                    type:'请输入正确的兑换数量',
                                    max:'兑换数量不能大于100',
                                    min:'请输入正确的兑换数量',
                                    pattern:'请输入正确的兑换数量'
                                }
                            },
                            {
                                type:'input',
                                modelKey:'take_name',
                                label:'收货人',
                                props:{
                                    type:'text',
                                    placeholder:'收货人'
                                },
                                rules:{
                                    required:true,
                                    type:'string',
                                    max:10
                                },
                                messages:{
                                    required:'请输入收货人',
                                    max:'收货人长度不能大于10'
                                }
                            },
                            {
                                type:'input',
                                modelKey:'take_phone',
                                label:'联系电话',
                                props:{
                                    type:'text',
                                    placeholder:'联系电话'
                                },
                                rules:{
                                    required:true,
                                    type:'number',
                                    pattern:/^1[3456789]\d{9}$/
                                },
                                messages:{
                                    required:'请输入联系电话',
                                    pattern:'请输入正确的联系电话'
                                }
                            },
                            {
                                type:areas,
                                modelKey:'area',
                                label:"所在地区",
                                rules:{
                                    required:true
                                }
                            },
                            {
                                type:"textarea",
                                modelKey:'address',
                                label:"收货地址",
                                props: {
                                    placeholder: "请输入收获地址"
                                },
                                rules:{
                                    required:true,
                                    min:1
                                }
                            }
                        ]
                },
                //地址管理插件
                plugin_address:{
                    use:false
                }
            }
        },
        mounted() {
            let inputs = this.$refs.create.querySelectorAll("input");
            inputs.forEach((item)=>{
                item.addEventListener("blur",()=>{
                    window.scroll(0,0);
                });
            });
            let textarea = this.$refs.create.querySelectorAll("textarea");
            textarea.forEach((item)=>{
                item.addEventListener("blur",()=>{
                    window.scroll(0,0);
                });
            });
        },
        computed:{
          //支付总价
          sum(){
            return this.goods.price * this.model.number;
          },
          //收货地址
          address(){
            let address = "";
            if(this.model.area.length > 0){
                address = this.model.area.join(" ");
            }
            return address+" "+this.model.address;
          },
          ...mapState({
              setting:"setting",
              member:"member",
              take_address:"take_address"
          })
        },
        watch:{
            take_address(value){
                this.model.take_name = value.name;
                this.model.take_phone = value.phone;
                this.model.address = value.area + value.address;
                this.model.plugin_address = value.name + " | " + value.phone + " | " + value.area + value.address;
            }
        },
        beforeRouteUpdate(to, from, next){
            this.transition_name = to.path.split('/').length < from.path.split('/').length ? "animate__animated animate__slideOutRight animate__faster animate__delay-2s" : "animate__animated animate__slideInRight animate__faster animate__delay-2s";
            setTimeout(()=>{
                next();
            },10);
        },
        created() {
            let {goods_id} = this.$route.params;
            this.goods_id = goods_id;
            this.getGoods();
            this.pluginAddress();
        },
        methods:{
            //Run
            /**
             * 获取商品详情
             */
            getGoods(){
                this.$url("goods/getGoodsApp",{
                    goods_id:this.goods_id
                })
                .then((res)=>{
                    if(res.data.status === "success"){
                        this.goods = res.data.data;
                        this.model.name = this.goods.name;
                    }
                });
            },
            /**
             *用户地址管理插件加载
             */
            pluginAddress(){
                plugin.tryRun('address')
                    .then((res)=>{
                        if(res){
                            this.plugin_address.use = true;
                            this.schema.fields.splice(2,10);
                            let field_address = {
                                type:takeAddress,
                                modelKey:'plugin_address',
                                label:'收货地址',
                                required:true,
                                events:{
                                    click:()=>{
                                        this.$router.push("/goods/create/take-address/1");
                                    }
                                }
                            }
                            this.schema.fields.push(field_address);
                            this.setNormalAddress();
                        }
                    })
            },
            /**
             * 获取设置默认地址
             */
            setNormalAddress(){
                this.$url("address/getNormal",{
                    uid:this.$sysinfo.uid
                },plugin.api)
                .then((res)=>{
                    if(res.data.status === "success"){
                        store.commit("setTakeAddress",res.data.data);
                    }
                });
            },

            //Handle
            /**
             * 创建订单
             */
            submit(){
                if(!this.submitCheck()) return;
                let createding = this.$createToast({
                    time: 0,
                    txt: '订单创建中',
                    type:"loading",
                    mask:true
                });
                createding.show();
                let {number,take_name,take_phone} = this.model;
                let data = {
                  uid:this.$sysinfo.uid,
                  goods_id:this.goods_id,
                  sum:this.sum,
                  number,
                  take_name,
                  take_phone,
                  address:this.address
                }
                this.$url("order/create",{
                  data
                })
                .then((res)=>{
                  createding.hide();
                  if(res.data.status === "success"){
                      this.$url("member/getMember",{
                          uid:this.$sysinfo.uid
                      })
                      .then((res)=>{
                          if(res.data.status === "success"){
                              store.commit("setMember",res.data.data);
                          }
                      });
                      this.$router.replace("/goods/create/order-detail/"+res.data.data);
                  }else{
                      this.$createToast({
                          time: 1500,
                          txt: res.data.err_msg,
                          type:"error",
                          mask:true
                      }).show();
                  }
                });
            },
            /**
             * 创建验证
             */
            submitCheck(){
                if(parseInt(this.goods.inventory) < this.model.number){
                    this.$createToast({
                        txt: '库存不足',
                        time: 1500,
                        mask:true,
                        type:"error"
                    }).show();
                    return false;
                }
                if(parseFloat(this.member.balance) < this.sum){
                    this.$createToast({
                        txt: this.setting.currency_name+'不足',
                        time: 1500,
                        mask:true,
                        type:"error"
                    }).show();
                    return false;
                }
                return true;
            },
            /**
             * 点击兑换按钮
             */
            createOrder(){
                this.$refs.form.submit();
            }
        }
    }
</script>

<style scoped lang="less" src="./create.less"></style>
